﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MetaDrive.Core;
using EnvDTE;
using EnvDTE80;
using MetaDrive.FluentCode;
using System.ComponentModel;

namespace MetaDrive.Library
{
    [SnippetInfo("NotifyPropertyChangedMixin")]
    public class NotifyPropertyChangedMixin : Snippet
    {
        protected override void OnBeforeProcess()
        {
            Source.Command.AddImport(typeof(INotifyPropertyChanged).Namespace);
        }
        
        protected override bool PreVisit(FluentCodeClass element)
        {
            return !element.Query.ImplementedInterfaces.Any(x => x.FullName == typeof(INotifyPropertyChanged).FullName);
        }

        protected override void Visit(FluentCodeClass element)
        {            
            element.Command.AddImplementedInterface(typeof(INotifyPropertyChanged).FullName);
            element.Command.AddEvent("PropertyChanged", "PropertyChangedEventHandler", vsCMAccess.vsCMAccessPublic);

            var propertyChangedFunction = element.Command.AddFunction("OnPropertyChanged", vsCMFunction.vsCMFunctionSub, "void", vsCMAccess.vsCMAccessProtected);
            propertyChangedFunction.Adaptee.CanOverride = true;
            propertyChangedFunction.Adaptee.AddParameter("name", "string", -1);

            propertyChangedFunction.Edit.Body = string.Format(
                "PropertyChangedEventHandler handler = PropertyChanged;\n" +
                "if (handler != null)\n" +
                "    handler(this, new PropertyChangedEventArgs(name));\n");
                     
            base.Visit(element);
        }
    }
}
